<template>
  <div class="index" id="index">
    <el-button @click="next" class="next" v-show="nextBtnShow">下一条</el-button>
    <el-button @click="pre" class="pre" v-show="nextBtnShow">上一条</el-button>
  </div>
</template>

<script>
  import * as esriLoader from "esri-loader";
  import { loadModules } from "esri-loader";
  import axios from "axios";
  import baseMap from "./components/baseMap";
  import {
    tileLayerConfig,
    PropData,
    productorIP,
    username,
    password
  } from "./map/mapconfig";

  import {
    changeImageLayer,
    mapGoTo,
    getDataBaseMap,
    addPoup,
    reduPoup
  } from "./map/mapHandle";
  export default {
    name: "",
    data() {
      return {
        nextBtnShow: false,
        map: null,
        view: null,
        token: "",
        TileLayer: null,
        Basemap: null,
        FeatureLayer: null,
        Zoom: null
      };
    },
    created() {
      this.initParams();
    },
    mounted() {
      this.InitMap();
    },
    methods: {
      initParams() {
        window["esri"] = this;
      },
      //缩小
      zoomOut() {
        let Zoom = this.Zoom;
        let view = this.view;
        var zoom = new Zoom({
          view
        });
        zoom.zoomOut();
      },
      //放大
      zoomIn() {
        let Zoom = this.Zoom;
        let view = this.view;
        var zoom = new Zoom({
          view
        });
        zoom.zoomIn();
      },
      //视角飞入
      // goTo(x, y, z) {
      //   let view = this.view;
      //   view.goTo({
      //     heading: 359.54,
      //     tilt: 0,
      //     position: {
      //       x: x,
      //       y: y,
      //       z: z,
      //       spatialReference: {
      //         wkid: 3857
      //       }
      //     }
      //   });
      // },
      goTo(x, y,zoom = 2) {
        let view = this.view;
        let shanghaiSpatialRef = new window['SpatialReference']({
          wkt: 'PROJCS["shanghaicity",' +
            'GEOGCS["GCS_Beijing_1954",' +
            'DATUM["D_Beijing_1954",' +
            'SPHEROID["Krasovsky_1940",6378245.0,298.3]],' +
            'PRIMEM["Greenwich",0.0],' +
            'UNIT["Degree",0.0174532925199433]],' +
            'PROJECTION["Transverse_Mercator"],' +
            'PARAMETER["False_Easting",-3457147.81],' +
            'PARAMETER["False_Northing",0.0],' +
            'PARAMETER["Central_Meridian",121.2751921],' +
            'PARAMETER["Scale_Factor",1.0],' +
            'PARAMETER["Latitude_Of_Origin",0.0],' +
            'UNIT["Meter",1.0]]',
        });
        view.goTo({
          center: new Point({
            x: x,
            y: y,
            spatialReference:{
              wkid: 3857
            }
          }),
          zoom: zoom
        })
      },

      //弹框
      btnShow(length) {
        if (length > 1) {
          this.nextBtnShow = true;
        } else {
          this.nextBtnShow = false;
        }
      },
      //添加地图
      mapAdd(id) {
        let FeatureLayer = this.FeatureLayer;
        let url = "";
        tileLayerConfig.forEach(item => {
          if (item.id == id) {
            url = item.url;
          }
        });
        let name = "map" + id;
        window[name] = new FeatureLayer({
          url: url,
          mode: FeatureLayer.MODE_ONDEMAND
        });
        window["BASEMAP"].add(window[name]);
      },
      mapRemove(id) {
        let name = "map" + id;
        window["BASEMAP"].remove(window[name]);
      },
      next() {
        addPoup();
      },
      pre() {
        reduPoup();
      },
      //修改底图
      changeBaseMap(url) {
        let Basemap = this.Basemap;
        let TileLayer = this.TileLayer;
        const basemap = new Basemap({
          baseLayers: [
            new TileLayer({
              url: url,
              opacity: 1
            })
          ]
        });
        this.map.basemap = basemap;
      },
      //点击地图，实现视角移动，图形高亮，信息查询

      //初始化地图
      InitMap() {
        let _that = this;
        esriLoader
          .loadModules([
            "esri/Basemap",
            "esri/identity/IdentityManager",
            "esri/views/MapView",
            "esri/Map",
            "esri/WebMap",
            "esri/views/SceneView",
            "esri/widgets/Zoom",
            "esri/Graphic",
            "esri/tasks/QueryTask",
            "esri/tasks/support/Query",
            "esri/views/draw/Draw",
            "esri/layers/GraphicsLayer",
            "esri/geometry/Point",
            "esri/geometry/Polyline",
            "esri/geometry/geometryEngine",
            "esri/Color",
            "esri/geometry/Polygon",
            "esri/layers/TileLayer",
            "esri/layers/FeatureLayer",
            "esri/core/watchUtils",
            "esri/geometry/SpatialReference",
          ])
          .then(
            ([
              Basemap,
              IdentityManager,
              MapView,
              Map,
              WebMap,
              SceneView,
              Zoom,
              Graphic,
              QueryTask,
              Query,
              Draw,
              GraphicsLayer,
              Point,
              Polyline,
              GeometryEngine,
              Color,
              Polygon,
              TileLayer,
              FeatureLayer,
              watchUtils,
              SpatialReference
            ]) => {
              _that.Zoom = Zoom;
              _that.TileLayer = TileLayer;
              _that.Basemap = Basemap;
              _that.FeatureLayer = FeatureLayer;
              window["Graphic"] = Graphic;
              window["QueryTask"] = QueryTask;
              window["Query"] = Query;
              window["Draw"] = Draw;
              window["Point"] = Point;
              window["Polyline"] = Polyline;
              window["Graphic"] = Graphic;
              window["GeometryEngine"] = GeometryEngine;
              window["Color"] = Color;
              window["Polygon"] = Polygon;
              window['SpatialReference'] = SpatialReference
              //获取token
              axios
                .get(
                  `http://10.89.5.191/onemap/tokens/generateToken?request=getToken&username=${username}&password=${password}&clientid=ref.${productorIP}/&expiration=500`
                )
                .then(function (response) {
                  _that.token = response.data;
                  window["TOKEN"] = response.data;
                  IdentityManager.registerToken({
                    server: "http://10.89.5.191/OneMapServer/rest/services",
                    token: _that.token
                  });

                  IdentityManager.on("dialog-create", function () {
                    IdentityManager.dialog.open = true;
                  });
                });
              const BASEMAP = new Basemap({
                baseLayers: [
                  new TileLayer({
                    url:
                      "http://10.89.5.191/OneMapServer/rest/services/zwdt_base/MapServer",
                    opacity: 1
                  })
                ]
              });

              var lineLayer = new GraphicsLayer(); //绘制线图层
              var polygonLayer = new GraphicsLayer(); //绘制面图层
              window["lineLayer"] = lineLayer;
              window["polygonLayer"] = polygonLayer;
              //创建map
              var map = new Map({
                basemap: BASEMAP,
                layers: [lineLayer, polygonLayer]
              });
              window["BASEMAP"] = map;
              _that.map = map;
              //创建三维对象
              var view = new MapView({
                container: "index",
                map: map,
                // viewingMode: "local",
                zoom: 2
              });
              window["view"] = view;
              window["pointGraphic"] = [];
              //移除系统的图标
              view.ui.remove("attribution");
              view.ui.remove("zoom");
              view.ui.move("compass", "top-right");
              view.ui.empty("top-left");
              _that.view = view;

              //加载全部FeatureLayer动态图层
              //  window['featureLayer'] = [];
              // tileLayerConfig.forEach((item)=>{
              //     // let name = 'map'+
              //     window[item.id] = new FeatureLayer({
              //         url:item.url,
              //         visible:item.visible,
              //          mode: FeatureLayer.MODE_ONDEMAND,
              //         dynamicDataSource: {
              //             type: "data-layer",
              //             dataSource: {
              //                 type: "table",
              //                 workspaceId: '1',
              //                 dataSourceName: '文件名'
              //             }
              //         }
              //     })
              //     window['BASEMAP'].layers.push(window[item.id]);
              // })
              // window['defaultTree'] = [31,51]
              //添加默认的图层
              changeImageLayer();
              //添加默认视角
              mapGoTo(-8017.253757247714, -3058.227434702489,2);
              // mapGoTo(-7665.641045334509,-3074.958167182762)
              // mapGoTo(-0.026032815205828216, -0.07291926350724934);
              //watchUtils
              watchUtils.watch(view.popup, "visible", function (value) {
                console.log(value);
                if (value == false) {
                  _that.nextBtnShow = false;
                } else if (value == true) {
                  _that.nextBtnShow = true;
                }
              });
              // watchUtils.whenTrue(view.popup, "visible", function(value) {
              //   console.log(value, "--true");
              // });
              //地图的点击事件
              view.on("click", function (e) {
                console.log(e);
                let x = e.mapPoint.x;
                let y = e.mapPoint.y;
                let dbStr = "";
                let PuopName = "";
                tileLayerConfig.forEach(item => {
                  window["tree"].forEach(item2 => {
                    if (item.id == item2 && item2 != 51) {
                      dbStr += "," + item.DB;
                    }
                  });
                  // if(item.id == window['tree'][window['tree'].length - 1]){
                  //     dbStr = item.DB;
                  //     // window['layName'] = item.name;
                  //     PuopName = item.name;
                  // }
                });
                dbStr = dbStr.substring(1, dbStr.length);
                if (dbStr) {
                  getDataBaseMap(x, y, dbStr, e, PuopName);
                }
              });
            }
          )
          .catch(err => {
            console.error(err);
          });
      }
    }
  };
</script>

<style scoped>
  .close {
    position: absolute;
    right: 20px;
    top: 50px;
    width: 50px;
    height: 50px;
    z-index: 0;
  }

  .next {
    position: fixed;
    top: 5%;
    right: 26%;
  }

  .pre {
    position: fixed;
    top: 11%;
    right: 26%;
  }

  .index {
    position: fixed;
    top: 0;
    left: 0;
    z-index: 0;
    height: 100vh;
    width: 100vw;
    background-color: #fff;
  }

  #index {
    height: 100vh;
    width: 100vw;
    position: absolute;
    top: 0;
    left: 0;
  }

  .tools {
    width: 150px;
    height: 600px;
    background: red;
    position: absolute;
    top: 5%;
    right: 5%;
  }

  /* .esri-view-surface.esri-view-surface--inset-outline::after{
    outline: none !important;
} */
</style>